package me.heizi.springboot.students.controllers.apis

import me.heizi.springboot.students.repositories.UserRepository
import me.heizi.springboot.students.security.TokenProvider
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import kotlin.IllegalArgumentException

@RestController
@RequestMapping("/api/login")
class LoginRest {


    @Autowired
    lateinit var repository: UserRepository
    @Autowired
    lateinit var tokens:TokenProvider

    data class LoginPTO(
        var id:String?,
        var pw:String?,
    ){
        constructor():this(null,null)
    }
    @PostMapping
    fun login(@Validated reqBody:LoginPTO):Any {

        require(reqBody.id!=null && reqBody.pw!=null) { IllegalArgumentException() }

        val r = repository.exist(reqBody.id!!,reqBody.pw!!)
        return when(r.size) {
            1 -> object { val token = tokens.genTokenAndSaveToken(r[0].id!!.toLong()) }
            0 -> throw NullPointerException()
            else -> throw IllegalStateException("${r.size} ")
        }
    }
}


